package com.ruoyi.functiontest.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.RoadSectionDistanceTest;
import com.ruoyi.functiontest.service.IRoadSectionDistanceTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 主线站点间里程实测数据测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/RoadSectionDistanceTest")
public class RoadSectionDistanceTestController extends BaseController
{
    @Autowired
    private IRoadSectionDistanceTestService roadSectionDistanceTestService;

    /**
     * 查询主线站点间里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadSectionDistanceTest:list')")
    @GetMapping("/list")
    public AjaxResult list(RoadSectionDistanceTest roadSectionDistanceTest)
    {
        List<RoadSectionDistanceTest> list = roadSectionDistanceTestService.selectRoadSectionDistanceTestList(roadSectionDistanceTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = roadSectionDistanceTest.getRoadName() != null && !roadSectionDistanceTest.getRoadName().isEmpty() ||
                                   roadSectionDistanceTest.getNodeName() != null && !roadSectionDistanceTest.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<RoadSectionDistanceTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出主线站点间里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadSectionDistanceTest:export')")
    @Log(title = "主线站点间里程实测数据测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RoadSectionDistanceTest roadSectionDistanceTest)
    {
        List<RoadSectionDistanceTest> list = roadSectionDistanceTestService.selectRoadSectionDistanceTestList(roadSectionDistanceTest);
        // 过滤出第二层和第三层数据，并将第一层的路段名称赋值给第二层
        List<RoadSectionDistanceTest> exportList = list.stream()
            .filter(item -> item.getParentId() != null && item.getParentId() > 0)
            .map(item -> {
                // 查找父节点并设置路段名称
                list.stream()
                    .filter(parent -> parent.getId().equals(item.getParentId()))
                    .findFirst()
                    .ifPresent(parent -> {
                        // 如果父节点是根节点(第一层)
                        if (parent.getParentId() == null || parent.getParentId() == 0) {
                            // 将第一层的路段名称赋值给第二层
                            item.setRoadName(parent.getRoadName());
                            // 将第一层的长度数据赋值给第二层的总长度字段
                            item.setTotalLeftLength(parent.getLeftLength());
                            item.setTotalRightLength(parent.getRightLength());
                            item.setTotalAvgLength(parent.getAvgLength());
                        }
                        // 如果父节点不是根节点(即当前节点为第三层)
                        else {
                            // 查找祖父节点并设置路段名称
                            list.stream()
                                .filter(grandParent -> grandParent.getId().equals(parent.getParentId()))
                                .findFirst()
                                .ifPresent(grandParent -> item.setRoadName(grandParent.getRoadName()));
                        }
                    });
                return item;
            })
            .collect(Collectors.toList());
        ExcelUtil<RoadSectionDistanceTest> util = new ExcelUtil<RoadSectionDistanceTest>(RoadSectionDistanceTest.class);
        util.exportExcel(response, exportList, "主线站点间里程实测数据测试数据");
    }

    /**
     * 获取主线站点间里程实测数据测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadSectionDistanceTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(roadSectionDistanceTestService.selectRoadSectionDistanceTestById(id));
    }

    /**
     * 新增主线站点间里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadSectionDistanceTest:add')")
    @Log(title = "主线站点间里程实测数据测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RoadSectionDistanceTest roadSectionDistanceTest)
    {
        return toAjax(roadSectionDistanceTestService.insertRoadSectionDistanceTest(roadSectionDistanceTest));
    }

    /**
     * 修改主线站点间里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadSectionDistanceTest:edit')")
    @Log(title = "主线站点间里程实测数据测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RoadSectionDistanceTest roadSectionDistanceTest)
    {
        return toAjax(roadSectionDistanceTestService.updateRoadSectionDistanceTest(roadSectionDistanceTest));
    }

    /**
     * 删除主线站点间里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadSectionDistanceTest:remove')")
    @Log(title = "主线站点间里程实测数据测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (roadSectionDistanceTestService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        
        return toAjax(roadSectionDistanceTestService.deleteRoadSectionDistanceTestByIds(ids));
    }
    
    /**
     * 构建树形结构
     */
    private List<RoadSectionDistanceTest> buildTree(List<RoadSectionDistanceTest> list) {
        // 构建父子关系映射
        Map<Long, RoadSectionDistanceTest> nodeMap = new HashMap<>();
        List<RoadSectionDistanceTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (RoadSectionDistanceTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (RoadSectionDistanceTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                RoadSectionDistanceTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<RoadSectionDistanceTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<RoadSectionDistanceTest> children = (List<RoadSectionDistanceTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }

}
